import http from '@/utils/httpRequest'
import moment from 'moment'

/**
* 格式化日期方法(带时分秒)
* 引用：import { formatDateTime } from '@/utils/common'
* 调用：formatDateTime('Dec 27, 2017 3:18:14 PM') 得到 '2017-12-27 15:18:14'
*/
export function formatDateTime (date) {
  if (!date) return ''
  let dateFormat = new Date(date)
  let year = dateFormat.getFullYear()
  let month = dateFormat.getMonth() + 1
  if (month < 10) month = '0' + month
  let mydate = dateFormat.getDate()
  if (mydate < 10) mydate = '0' + mydate
  let hours = dateFormat.getHours()
  if (hours < 10) hours = '0' + hours
  let minutes = dateFormat.getMinutes()
  if (minutes < 10) minutes = '0' + minutes
  let seconds = dateFormat.getSeconds()
  if (seconds < 10) seconds = '0' + seconds
  let time = `${year}-${month}-${mydate} ${hours}:${minutes}:${seconds}`
  return time
}

/**
* 格式化日期方法（不带时分秒）
* 引用：import { formatDate } from '@/utils/common'
* 调用：formatDate('Dec 27, 2017 3:18:14 PM') 得到 '2017-12-27'
*/
export function formatDate (date) {
  if (!date) return ''
  let dateFormat = new Date(date)
  let year = dateFormat.getFullYear()
  let month = dateFormat.getMonth() + 1
  if (month < 10) month = '0' + month
  let mydate = dateFormat.getDate()
  if (mydate < 10) mydate = '0' + mydate
  let time = `${year}-${month}-${mydate}`
  return time
}

/**
* 获取两个时间相差的天数
* 引用：import { getDays } from '@/utils/common'
* 调用：getDays('2019-3-1', '2019-3-2') 得到 2
*/
export function getDays (endDateStr, startDateStr) {
  if (!endDateStr) return ''
  if (!startDateStr) return ''
  let endDate = new Date(formatDate(endDateStr))
  let startDate = new Date(formatDate(startDateStr))
  let longTime = endDate.getTime() - startDate.getTime()
  let days = parseInt(longTime / (1000 * 60 * 60 * 24))
  return days + 1
}

/**
 * 时间范围选择 快捷方式
 * 引用：import { dateSelectShorts } from '@/utils/common'
 * 调用：dateSelectShorts()
 */
export function dateSelectShorts () {
  return [{
    text: '最近一周',
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一个月',
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近三个月',
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近六个月',
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一年',
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
      picker.$emit('pick', [start, end])
    }
  }]
}

/**
* 格式化日期方法（不带时分秒）
* 引用：import { formatDateByPattern } from '@/utils/common'
* 调用：formatDateByPattern('Dec 27, 2017 3:18:14 PM', 'YYYY-MM-DD') 得到 '2017-12-27'
*/
export function formatDateByPattern (dateStr, pattern) {
  if (dateStr) {
    return (dateStr === null || dateStr === '') ? '' : moment(dateStr).format(pattern)
  } else {
    return ''
  }
}

/**
* 根据typeCode获取字典项list
* 引用：import { getConstantCodeList } from '@/utils/common'
* getConstantCodeMap('PAY_MODE')
* 参数 typeCode 字典项类别
*/
export function getConstantCodeMap (typeCode) {
  return http({
    url: http.requestUrl('/common/constantcode/listForSelect'),
    method: 'get',
    params: http.requestParams({
      'typeCode': typeCode
    }),
    headers: {
      isLoading: false
    }
  })
}

/**
* 通过常量id，获取常量名称
* 引用：import { getConstantName } from '@/utils/common'
* getConstantName(typeCode, constantCode)
*/
export function getConstantName (typeCode, constantCode) {
  return http({
    url: http.requestUrl('/common/constantcode/getConstantName'),
    method: 'get',
    params: http.requestParams({
      'typeCode': typeCode,
      'constantCode': constantCode
    }),
    headers: {
      isLoading: false
    }
  })
}

/**
* 获取附件list
* 引用：import { getAttachmentList } from '@/utils/common'
* getAttachmentList(linkTable, linkId, linkField)
*/
export function getAttachmentList (linkTable, linkId, linkField) {
  return http({
    url: http.requestUrl('/common/attachment/getAttachmentList'),
    method: 'get',
    params: http.requestParams({
      'linkTable': linkTable,
      'linkId': linkId,
      'linkField': linkField
    })
  })
}


/**
* 获取公司list
* 引用：import { getCompanyList } from '@/utils/common'
* getCompanyList()
* 参数
*/
export function getCompanyList (keyword) {
  return http({
    url: http.requestUrl('/common/companyinfo/getCompanyList'),
    method: 'get',
    params: http.requestParams({
      'keyword': keyword
    })
  })
}

/**
* 根据公司id获取公司信息
* 引用：import { getCompanyById } from '@/utils/common'
* getCompanyById(companyId)
* 参数 companyId 公司id
*/
export function getCompanyById (companyId) {
  return http({
    url: http.requestUrl('/common/companyinfo/getCompanyById'),
    method: 'get',
    params: http.requestParams({
      'companyId': companyId
    })
  })
}

/**
* 获取专家list
* 引用：import { getExpertList } from '@/utils/common'
* getExpertList()
* 参数
*/
export function getExpertList (keyword) {
  return http({
    url: http.requestUrl('/common/expertinfo/getExpertList'),
    method: 'get',
    params: http.requestParams({
      'keyword': keyword
    })
  })
}

/**
* 根据专家id获取专家信息
* 引用：import { getExpertById } from '@/utils/common'
* getExpertById(expertId)
* 参数 expertId 专家id
*/
export function getExpertById (companyId) {
  return http({
    url: http.requestUrl('/common/expertinfo/getExpertById'),
    method: 'get',
    params: http.requestParams({
      'expertId': expertId
    })
  })
}


/**
 * <span>{{1478511 | formatMoney}}</span>
 */
const digitsRE = /(\d{3})(?=\d)/g
export function formatMoney (value, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

/**
 * 获取绝对值
 * @param {*} value
 */
export function absNumber (value) {
  value = parseFloat(value)
  return Math.abs(value)
}

/**
 * 本周第一天(周六)
 */
export const getWeekFirstDay = function () {
  var nowDate = new Date()
  var day = nowDate.getDay()
  if (day === 0) {
    day = 7
  }
  var weekFirstDay = new Date(nowDate - (day - 1) * 86400000)
  return weekFirstDay
}

/**
 * 本周最后一天（周五）
 */
export const getWeekLastDay = function () {
  var nowDate = new Date()
  var day = nowDate.getDay()
  if (day === 0) {
    day = 7
  }
  var weekFirstDay = new Date(nowDate - (day - 1) * 86400000)
  var weekLastDay = new Date((weekFirstDay / 1000 + 6 * 86400) * 1000)
  return weekLastDay
}

/**
 * 本月第一天
 */
export const getMonthFirstDay = function () {
  var nowDate = new Date()
  var monthFirstDay = new Date(nowDate.getFullYear(), nowDate.getMonth(), 1)
  return monthFirstDay
}

/**
 * 本月最后一天
 */
export const getMonthLastDay = function () {
  var nowDate = new Date()
  var monthNextFirstDay = new Date(nowDate.getFullYear(), nowDate.getMonth() + 1, 1)
  var monthLastDay = new Date(monthNextFirstDay - 86400000)
  return monthLastDay
}

/**
 * 指定日期增加天数
 */
export const addDays = function (mydate, days) {
  var newDate = new Date(mydate.getTime() + days * 24 * 60 * 60 * 1000)
  return newDate
}

/**
 * 是否闰年
 * @param {*} year
 */
export const isLeapYear = function (year) {
  return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
}

/**
 * 根据年月获取月天数
 * @param {*} year
 * @param {*} month
 */
export const getDaysInMonth = function (year, month) {
  return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
}

/**
 * 指定日期增加数
 */
export const dateAdd = function (type, number, date) {
  switch (type) {
    case 'year' : {
      date.setFullYear(date.getFullYear() + number)
      return date
    }
    case 'month': {
      // date.setMonth(date.getMonth() + number)
      var n = date.getDate()
      date.setDate(1)
      date.setMonth(date.getMonth() + number)
      var year = date.getFullYear()
      var month = date.getMonth()
      date.setDate(Math.min(n, getDaysInMonth(year, month)))
      return date
    }
    case 'month-tb' : {
      date.setFullYear(date.getFullYear() + number)
      return date
    }
    case 'week' : {
      date.setDate(date.getDate() + number * 7)
      return date
    }
    case 'day' : {
      date.setDate(date.getDate() + number)
      return date
    }
    default : {
      date.setDate(date.getDate() + number)
      return date
    }
  }
}

/**
 * 是否手机端
 */
export function _isMobile () {
  let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return flag
}

/**
 * Parse the time to string datax用到
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}
